<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学员姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学员姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学号" prop="studentNo">
        <el-input
          v-model="queryParams.studentNo"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="科目" prop="subjectCode">
        <el-select v-model="queryParams.subjectCode" placeholder="请选择科目" clearable>
          <el-option
            v-for="subject in subjectOptions"
            :key="subject.subjectCode"
            :label="subject.subjectName"
            :value="subject.subjectCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="待考试" value="待考试" />
          <el-option label="已完成" value="已完成" />
          <el-option label="已取消" value="已取消" />
        </el-select>
      </el-form-item>
      <el-form-item label="安排时间" prop="scheduledTime">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['jiaxiao:retake:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['jiaxiao:retake:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['jiaxiao:retake:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['jiaxiao:retake:export']"
        >导出</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-calendar"
          size="mini"
          @click="showCalendar"
        >日历视图</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="retakeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学号" align="center" prop="studentNo" />
      <el-table-column label="学员姓名" align="center" prop="studentName" />
      <el-table-column label="科目" align="center" prop="subjectName" />
      <el-table-column label="安排时间" align="center" prop="scheduledTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scheduledTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['jiaxiao:retake:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status === '待考试'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleComplete(scope.row)"
            v-hasPermi="['jiaxiao:retake:edit']"
          >完成</el-button>
          <el-button
            v-if="scope.row.status === '待考试'"
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleCancel(scope.row)"
            v-hasPermi="['jiaxiao:retake:edit']"
          >取消</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['jiaxiao:retake:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改补考安排对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学员" prop="studentId">
          <el-select v-model="form.studentId" placeholder="请选择学员" @change="handleStudentChange">
            <el-option
              v-for="student in studentOptions"
              :key="student.studentId"
              :label="student.name + '(' + student.studentNo + ')'"
              :value="student.studentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="科目" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择科目">
            <el-option
              v-for="subject in subjectOptions"
              :key="subject.subjectId"
              :label="subject.subjectName"
              :value="subject.subjectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="安排时间" prop="scheduledTime">
          <el-date-picker
            v-model="form.scheduledTime"
            type="datetime"
            placeholder="选择安排时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="待考试">待考试</el-radio>
            <el-radio label="已完成">已完成</el-radio>
            <el-radio label="已取消">已取消</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 日历视图对话框 -->
    <el-dialog title="补考日程日历" :visible.sync="calendarVisible" width="90%" append-to-body>
      <RetakeCalendar />
    </el-dialog>
  </div>
</template>

<script>
import { listRetakeSchedule, getRetakeSchedule, delRetakeSchedule, addRetakeSchedule, updateRetakeSchedule, completeRetakeSchedule, cancelRetakeSchedule, getRetakeScheduleByDateRange } from "@/api/jiaxiao/retake";
import { listStudent } from "@/api/jiaxiao/student";
import { listSubject } from "@/api/jiaxiao/subject";
import RetakeCalendar from "./components/RetakeCalendar.vue";

export default {
  name: "RetakeSchedule",
  components: {
    RetakeCalendar
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 补考安排表格数据
      retakeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示日历
      calendarVisible: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        studentName: null,
        studentNo: null,
        subjectCode: null,
        status: null,
        scheduledTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        studentId: [
          { required: true, message: "学员不能为空", trigger: "change" }
        ],
        subjectId: [
          { required: true, message: "科目不能为空", trigger: "change" }
        ],
        scheduledTime: [
          { required: true, message: "安排时间不能为空", trigger: "change" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 学员选项
      studentOptions: [],
      // 科目选项
      subjectOptions: []
    };
  },
  created() {
    this.getList();
    this.getStudentOptions();
    this.getSubjectOptions();
  },
  methods: {
    /** 查询补考安排列表 */
    getList() {
      this.loading = true;
      listRetakeSchedule(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.retakeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取学员选项 */
    getStudentOptions() {
      listStudent({}).then(response => {
        this.studentOptions = response.rows;
      });
    },
    /** 获取科目选项 */
    getSubjectOptions() {
      listSubject({}).then(response => {
        this.subjectOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        retakeId: null,
        studentId: null,
        subjectId: null,
        scheduledTime: null,
        status: "待考试",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.retakeId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加补考安排";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const retakeId = row.retakeId || this.ids
      getRetakeSchedule(retakeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改补考安排";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.retakeId != null) {
            updateRetakeSchedule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRetakeSchedule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const retakeIds = row.retakeId || this.ids;
      this.$modal.confirm('是否确认删除补考安排编号为"' + retakeIds + '"的数据项？').then(function() {
        return delRetakeSchedule(retakeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 完成按钮操作 */
    handleComplete(row) {
      this.$modal.confirm('是否确认完成补考安排？').then(function() {
        return completeRetakeSchedule(row.retakeId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 取消按钮操作 */
    handleCancel(row) {
      this.$modal.confirm('是否确认取消补考安排？').then(function() {
        return cancelRetakeSchedule(row.retakeId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jiaxiao/retake/export', {
        ...this.queryParams
      }, `retake_${new Date().getTime()}.xlsx`)
    },
    /** 显示日历视图 */
    showCalendar() {
      this.calendarVisible = true;
      this.$nextTick(() => {
        this.initCalendar();
      });
    },
    /** 初始化日历 */
    initCalendar() {
      // 获取当前月份的数据
      const now = new Date();
      const startDate = new Date(now.getFullYear(), now.getMonth(), 1);
      const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      getRetakeScheduleByDateRange(
        this.formatDate(startDate, 'yyyy-MM-dd'),
        this.formatDate(endDate, 'yyyy-MM-dd')
      ).then(response => {
        this.renderCalendar(response.data);
      });
    },
    /** 渲染日历 */
    renderCalendar(data) {
      // 这里可以使用第三方日历组件，如FullCalendar
      // 简化实现，显示数据列表
      console.log('Calendar data:', data);
    },
    /** 学员选择变化 */
    handleStudentChange(studentId) {
      // 可以在这里添加根据学员获取科目的逻辑
    },
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      switch(status) {
        case '待考试': return 'warning';
        case '已完成': return 'success';
        case '已取消': return 'danger';
        default: return '';
      }
    },
    /** 格式化日期 */
    formatDate(date, fmt) {
      const o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds(),
        'q+': Math.floor((date.getMonth() + 3) / 3),
        'S': date.getMilliseconds()
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (const k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
      }
      return fmt;
    }
  }
};
</script>
